export default {
	namespaced:true,
	state:{
		yf:90,
		// { goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state }
		cart:uni.getStorageSync('cart') || []
	},
	mutations:{
		addToCart(state,goods){
			const findResult = state.cart.find(x => x.goods_id===goods.goods_id)
			if(!findResult){
				state.cart.push(goods)
			}else {
				findResult.goods_count++
			}
			this.commit("mcart/saveToStorage")
		},
		saveToStorage(state) {
		   uni.setStorageSync('cart', state.cart)
		},
		// 修改购物车状态的
		changeRadioState(state,{goods_id,goods_state}){
			const result = state.cart.find(x=>x.goods_id==goods_id)
			result.goods_state = !goods_state
			this.commit('mcart/saveToStorage')
		},
		// 修改商品的数量
		changeGoodsCount(state,{goods_id,goods_count}){
			const result = state.cart.find(x=>x.goods_id==goods_id)
			result.goods_count = goods_count
			this.commit('mcart/saveToStorage')
		},
		// 删除商品
		deleteGoods(state,goods_id){
			const newCart = state.cart.filter(x=>x.goods_id!==goods_id) 
			state.cart = newCart
			this.commit('mcart/saveToStorage')
		},
		// 全选全不选
		changeFullState(state,bool){
			state.cart.forEach(item=>item.goods_state=bool)
			this.commit('mcart/saveToStorage')
		}
		
	},
	getters:{
		total(state) {
		      let c = 0
		      // 循环统计商品的数量，累加到变量 c 中
			  // for(let i =0;i<state.cart.length;i++){
				 //  c += state.cart[i].goods_count
			  // }
		      state.cart.forEach(goods => c += goods.goods_count)
		      return c
		},
		// 统计当前选中商品的数量
		isCheckedCount(state){
			// console.log(state.cart.filter(x => x.goods_state).reduce((total, item) => total += item.goods_count, 0));
			return state.cart.filter(x => x.goods_state).reduce((total, item) => total += item.goods_count, 0)
		},
		// 勾选商品、总价
		checkedPrice(state){
			return state.cart.filter(x=>x.goods_state).reduce((total,item)=>total += item.goods_count*item.goods_price,0).toFixed(2)
		}
		   
	}
}